package com.yang.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yang.exception.BusinessException;
import com.yang.mapper.ArchivesMapper;
import com.yang.mapper.RoleMapper;
import com.yang.mapper.UserInfoMapper;
import com.yang.pojo.Archives;
import com.yang.pojo.Role;
import com.yang.pojo.UserInfo;
import com.yang.responseEntity.Employeeleave;
import com.yang.responseEntity.Interns;
import com.yang.responseEntity.regularEmployee;
import com.yang.service.ArchivesService;
import com.yang.service.RoleService;
import com.yang.service.UserInfoService;
import com.yang.util.*;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @Author 杨天可
 * @Date 2021/3/8 16:43
 * @Version 1.0
 */

@Transactional
@RestController
@RequestMapping("/userInfo")
public class UserInfoController {

    @Resource
    RoleService roleService;
    @Resource
    UserInfoService userInfoService;
    @Resource
    RoleMapper roleMapper;
    @Resource
    ArchivesService archivesService;
    @Resource
    ArchivesMapper archivesMapper;

    /***
     * 根据id查找用户
     * @param id
     * @return
     */
    @GetMapping("/getUserInfoById")
    public Map<String,Object> getUserInfoById(@RequestParam("id") Integer id){
        JsonResult jsonResult = new JsonResult();
        UserInfo userinfo = userInfoService.findById(id);
        Role byId = roleMapper.findById(userinfo.getRoleId());
        userinfo.setRole(byId);
        jsonResult.setCode("200");
        jsonResult.setData(userinfo);
        return jsonResult.getValues();
    }

    /***
     * 用户列表分页
     * @param username
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/getUserInfoListByPage")
    public Map<String,Object> getUserInfoListByPage(@RequestParam("username")String username, @RequestParam("page")Integer page, @RequestParam("pageSize")Integer pageSize){
        JsonResult jsonResult = new JsonResult();
        PageHelper.startPage(page,pageSize);
        List<UserInfo> userInfoListByPage = userInfoService.getUserInfoListByPage(username);
        PageInfo<UserInfo> info = new PageInfo<>(userInfoListByPage);
        jsonResult.setCode("200");
        jsonResult.setData(info);
        return  jsonResult.getValues();
    }

    /***
     * 删除（停用）当前用户
     * @param id
     * @return
     */
    @GetMapping("/deleteUserInfoById")
    public Map<String,Object> deleteUserInfoById(@RequestParam("id")Integer id){
        JsonResult jsonResult = new JsonResult();
        userInfoService.deleteUserInfoById(id);
        jsonResult.setCode("200");
        jsonResult.setMsg("删除成功");
        return jsonResult.getValues();
    }

    /***
     * 新增或修改用户信息
     * @param userInfo
     * @return
     */
    @PostMapping("/saveOrUpdate")
    public Map<String,Object> saveOrUpdate(@RequestBody UserInfo userInfo) throws Exception {
        JsonResult jsonResult = new JsonResult();
        if(userInfo.getId() == null){//新增
            if(userInfo.getDepartmentId() == null){
                throw new BusinessException("未选择部门");
            }
            if(userInfo.getWorkType() == null){
                //用户工作类型默认为全职
                userInfo.setWorkType(Constants.WROK_TYPE);
            }
            //用户密码加密
            userInfo.setPassword(EncryptionUtil.password(userInfo.getPassword()));
            //用户默认角色为员工
            Role byId = roleMapper.findById(Constants.ROLE_ID_NEW_REGISTER);
            userInfo.setRole(byId);
            userInfo.setInsertTime(new Date());
            userInfo.setUpdateTime(new Date());
            userInfo.setIsEnd(0);
            int save = userInfoService.save(userInfo);
            if(save > 0 ){
                jsonResult.setMsg("添加成功");
                jsonResult.setCode("200");
            }else{
                throw  new BusinessException("系统开小差");
            }
        }else{//修改
            UserInfo byId = userInfoService.findById(userInfo.getId());
            if(!byId.getDepartmentId().equals(userInfo.getDepartmentId())){
                //说明用户修改了部门，修改部门也需要将工号修改
                Archives byId1 = archivesMapper.findById(userInfo.getDepartmentId());
                NumberGeneration numberGeneration = new NumberGeneration();
                byId1.setJobNumber(numberGeneration.jobNumber(userInfo.getDepartmentId(),userInfo.getPhoneNumber()));
                archivesService.update(byId1);
            }
            userInfo.setPassword(EncryptionUtil.password(userInfo.getPassword()));
            userInfo.setUpdateTime(new Date());

            if (userInfo.getIsEnd() == 1){
                /***
                 *  删除了该用户（需要人事，或者系统管理员才能进行的操作，这里涉及到权限，前端需要根据RoleId进行控件的渲染）
                 *  1.如果删除了该用户，那么该用户对应的详细资料，合同，也应该失效（代表失效字段视具体表而定）
                 *  2.应该立马计算该用户的工资并将消息通知给管理人员（人事部门员工）
                 */
                userInfoService.deleteUserInfoById(userInfo.getId());

            }
            int update = userInfoService.update(userInfo);
            if (update > 0 ){
                jsonResult.setCode("200");
                jsonResult.setMsg("修改成功");
            }else{
                throw  new BusinessException("系统开小差");
            }

        }

        return jsonResult.getValues();
    }

    /***
     * 根据Token获取用户信息
     * @param request
     * @param response
     * @return
     */
    @PostMapping("/getUserInfoBYToken")
    public Map<String,Object> getUserInfoBYToken(HttpServletRequest request, HttpServletResponse response){
        JsonResult jsonResult = new JsonResult();
        response.setHeader("Content-type", "application/json;charset=UTF-8");
        String token = request.getHeader("token");
        Integer userInfoId = JwtUtil.getUserInfoId(token);
        UserInfo userInfoDB = userInfoService.findById(userInfoId);
        userInfoDB.setRole(roleService.findById(userInfoDB.getRoleId()));
        jsonResult.setCode("200");
        jsonResult.setData(userInfoDB);
        return jsonResult.getValues();
    }

    /***
     * 员工管理 -- 员工花名册
     * @param username 根据用户名模糊查询（如果不查找就传空值）
     * @param page 当前页
     * @param pageSize 每页大小
     * @param workType 在职类型  0：全职  2：实习
     * @param isEnd 是否查找离职员工列表 （如果需要查找传参数：1，不需要查找传空值）
     * @return
     */
    @PostMapping("/getEmployeeInfoByPage")
    public Map<String,Object> getEmployeeInfoByPage(@RequestParam("username")String username,@RequestParam("page")Integer page,
                                                    @RequestParam("pageSize")Integer pageSize,@RequestParam("workType")Integer workType,@RequestParam("isEnd")Integer isEnd){
        JsonResult jsonResult = new JsonResult();
        try{
            PageHelper.startPage(page,pageSize);
            if(workType == 0){//查找正式员工
                List<regularEmployee> userInfoList = userInfoService.getUserInfoList(username, workType);
                jsonResult.setCode("200");
                jsonResult.setData(userInfoList);
            }
            if(workType == 2){//实习员工列表
                List<Interns> userInfoList = userInfoService.getUserInfoListInterns(username, workType);
                jsonResult.setCode("200");
                jsonResult.setData(userInfoList);
            }
            if(isEnd != null && isEnd == 1){//离职员工列表
                List<Employeeleave> userInfoList = userInfoService.getUserInfoListLeave(username);
                jsonResult.setCode("200");
                jsonResult.setData(userInfoList);
            }
        }catch(Exception e){
            e.printStackTrace();
            jsonResult.setMsg("系统开小差");
            jsonResult.setCode("500");
        }
        return jsonResult.getValues();
    }
}
